/*
 * tester.cpp
 *  Created on: Mar 24, 2012
 *      Author: Stephen
 */
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>

#include <windows.h> /* WINSPEC */

#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_mixer.h>

#include "grav.h"
#include "ttimer.h"

const int RBOUND = 600;
const int DBOUND = 400;
const int FPS = 30;


void initAll();
void quitAll();
void looper();
void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination);

int frame = 0;
Timer update;

SDL_Surface *screen;
/*SDL_Surface *bg;*/
SDL_Surface *message;
SDL_Surface *objstuff;
SDL_Event event;

SDL_Rect clground;

TTF_Font *font = NULL;
SDL_Color textC = {255,255,255};
SDL_Color textG = {0,255,0};

Mix_Music *mainm = NULL;

bool playing = false;

using std::abs;

int main( int argc, char* args[] )
{
	FreeConsole(); /* WINSPEC */
	//START
	initAll();
	//INITIALIZED, BEGIN TTF
	message = TTF_RenderText_Solid(font,"Tester", textC);
	/*apply_surface(0,0,bg,screen);*/
	apply_surface(100,100,message,screen);

	SDL_Flip(screen);

	// TTF'D, BEGIN LOOP
	looper();
	//QUITTING
	quitAll();
	return 0;
}

void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination)
{
    //Holds offsets
    SDL_Rect offset;

    //Get offsets
    offset.x = x;
    offset.y = y;

    //Blit
    SDL_BlitSurface( source, NULL, destination, &offset );
}

void looper()
{
	bool run = true;
	update.start();
	rect wordpos;
	wordpos.x = 100;
	wordpos.y = 100;
	Obj wordgrav(100,100,1);
	wordgrav.accel(0,1);
	wordgrav.veloc(200,-2);

	std::ostringstream bah;
	std::stringstream caption;

	while(run){
		while(SDL_PollEvent(&event))
		{
			switch(event.type)
			{
			case SDL_QUIT:
			case SDL_MOUSEBUTTONDOWN:
				run = false; break;
			case SDL_KEYDOWN:
				if(event.key.state == SDL_PRESSED)
				{
					if(event.key.keysym.sym == SDLK_UP)
						wordgrav.velocy(wordgrav.velocity().y - 20);
					else if(event.key.keysym.sym == SDLK_DOWN)
						wordgrav.velocy(wordgrav.velocity().y + 20);
					else if(event.key.keysym.sym == SDLK_LEFT)
						wordgrav.velocx(wordgrav.velocity().x - 20);
					else if(event.key.keysym.sym == SDLK_RIGHT)
						wordgrav.velocx(wordgrav.velocity().x + 20);
					else if(event.key.keysym.sym == SDLK_RETURN)
					{
						if(playing)
						{
							Mix_HaltMusic();
							playing = false;
						}
						else
						{
							playing = true;
							if(Mix_PlayMusic(mainm,-1)==-1)
								fprintf(stderr, "ERROR play music failed.");
						}
					}
				}
				break;
			default: break;
			} //END SWITCH
		} //END POLL EVENT



		//COLLISION
		wordgrav.accelx(0 - (wordgrav.velocity().x / 10));
		if(wordpos.x <= 0)
			//wordgrav.velocx(0 - (wordgrav.velocity().x / 1.2));
			wordgrav.velocx((0 < wordgrav.velocity().x ? wordgrav.velocity().x : 0 - wordgrav.velocity().x));
		else if(wordpos.x >= RBOUND)
			wordgrav.velocx((0 < wordgrav.velocity().x ? 0 - wordgrav.velocity().x : wordgrav.velocity().x));

		if(wordpos.y >= DBOUND)
		{
			if(wordgrav.velocity().y < 1 && wordgrav.velocity().y > -1)
				wordgrav.velocy(0);
			else
				wordgrav.velocy((0 < wordgrav.velocity().y ? 0 - wordgrav.velocity().y/1.5 : wordgrav.velocity().y/1.5));
		}
		else if(wordpos.y <= 0)
		{
			if(wordgrav.velocity().y < 1 && wordgrav.velocity().y > -1)
				wordgrav.velocy(0);
			else
				wordgrav.velocy((0 < wordgrav.velocity().y ? wordgrav.velocity().y/1.5 : 0 - wordgrav.velocity().y/1.5));
		}
		/*
		if((wordpos.y >= DBOUND || wordpos.y <= 0) && !(wordgrav.velocity().y < 1 && wordgrav.velocity().y > -1))
			wordgrav.velocy(0 - wordgrav.velocity().y / 1.5);
		else if(wordgrav.gettime() != 0 && (wordpos.y >= DBOUND || wordpos.y <= 0)
				&& (wordgrav.velocity().y < 1 && wordgrav.velocity().y > -1))
		{
			wordgrav.velocy(0);
			//wordgrav.settime(0);
		}
		*/

		//update position
		wordpos = wordgrav.update();
		//update based on FPS, 30 FPS correlates to 1 second.
		//wordpos = wordgrav.update(30 / FPS);

		//clear screen for update
		SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0, 0, 0));
		SDL_FillRect(screen, &clground, SDL_MapRGB(screen->format, 255, 255, 255));

		//On Screen text
		bah.clear();
		bah.str("");
		bah << std::showpoint << "Total Vel: " << sqrt(pow(wordgrav.velocity().x,2) + pow(wordgrav.velocity().y,2));
		objstuff = TTF_RenderText_Solid(font,bah.str().c_str(), textG);

		//Apply surfaces

		apply_surface((int)wordpos.x,(int)wordpos.y,message,screen);
		apply_surface(0,0,objstuff,screen);


		SDL_Flip(screen);
		frame++;

		if(update.get_ticks() < 1000 / FPS)
			SDL_Delay((1000 / FPS) - update.get_ticks());

		caption.clear();
		caption.str("");
		caption << "FPS: " << (frame / ( update.get_ticks() / 1000.f )) << "Vely: " << wordgrav.velocity().y;
		update.reset();
		frame = 0;
		SDL_WM_SetCaption(caption.str().c_str(),NULL);

/*
		if(update.get_ticks() > 1000)
		{
			std::stringstream caption;

			caption << "FPS: " << (frame / ( update.get_ticks() / 1000.f ));
			update.reset();
			frame = 0;
			SDL_WM_SetCaption(caption.str().c_str(),NULL);
		}
*/
	}
}

void initAll()
{
	//Start SDL
	SDL_Init( SDL_INIT_EVERYTHING );

	if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1)
	{
		fprintf(stderr, "ERROR loading SDL_mixer.");
		quitAll();
		exit(1);
	}
	mainm = Mix_LoadMUS("SFRX.mp3");
	if(mainm == NULL)
	{
		fprintf(stderr, "ERROR loading SFRX.mp3");
		quitAll();
		exit(1);
	}


	screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
	if(screen == NULL){
		fprintf(stderr, "ERROR Setting video mode to 640x480x32 mode.");
		quitAll();
		exit(1);
	}

	clground.x = 0;
	clground.y = DBOUND + 17;
	clground.w = 640;
	clground.h = 480 - DBOUND - 17;

	/*bg = IMG_Load("640x480xb.png");*/

	if(TTF_Init() == -1)
	{
		fprintf(stderr,"ERROR TTF failed to initialize.");
		quitAll();
		exit(1);
	}
	SDL_WM_SetCaption("BLURBA!",NULL);

	font = TTF_OpenFont("courbd.ttf",20);

	if(font == NULL)
	{
		fprintf(stderr,"ERROR font not found");
		quitAll();
		exit(1);
	}
}

void quitAll()
{
	SDL_FreeSurface(message);
	/*SDL_FreeSurface(bg);*/
	SDL_FreeSurface(screen);
	//Quit SDL
	Mix_FreeMusic(mainm);
	Mix_Quit();
	SDL_Quit();
}
